/* $RCSFile: CRMImageSingle.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ImageManager/PageModules/CRMImage/CRMImageSingle.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:56:46  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 7 2010/08/09 09:44:02  christian.surieux
 *   Added Log to cs sources files
 */

using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.Settings;
using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Helpers;
using AddonNice.Diagnostics;
using AddonNice.Security;

using AddonNice.CRMImage;
using AddonNice.Settings.CRMImage;
using AddonNice.CRMImage.UI.WebControls;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;
using AddonNice.CRMWrapper.CRMImage;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;


namespace AddonNice.PageModules.CRMImage
{

    /// <summary>
	/// Addon Nice Portal CRMImageSingle module: used as an inserted page in a Crm IFrame
	/// </summary>
    public partial class CRMImageSingle :  PortalCrmImageModuleControl
    {
		#region local vars
        #endregion local vars

		#region Global Implementation

        /// <summary>
		/// GuidID
		/// </summary>
		public override Guid GuidID 
		{
			get
			{
                return new Guid(ImStr.CRMImageSingleGuid);
			}
		}

        public override bool DependsFromCustomCrmEntities
        {
            get{ return true;}
        }
        
        /// <summary>
        /// SortedList of entities/version from which this module depends, schema name is the key, version is a string in the form major.minor
        /// </summary>
        public override SortedList<string,string> RelatedCustomEntities
        {
            get
            {
                SortedList<string,string> Lst =   new SortedList<string,string>();
                Lst.Add(ImStr.adnimage,"1.0");
                return Lst;
            }
        }

        #endregion

        public override bool CanAdd
        {
            get
            {
                bool ret    =   false;
                // Module should be installed first
                if (  UseSettingsFromAnotherModule )
                    ret     =   base.CanAdd;
                if ( CrmImageTrace.Sw.TraceInfo )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[I]CRMImageSingle CanAdd GET ModuleId: {0}, CanAdd: {1}, AuthorizedAddRoles : {2}", ModuleID, ret, ModuleBaseConfiguration.AuthorizedAddRoles),CrmImageTrace.Sw.Info);
                return ret;
            }
        }

        Guid CRMImageGuidId =   new Guid(ImStr.CRMImageGuid);
        /// <summary>
        /// Potential familly modules for sharing settings
        /// </summary>
        public override Guid ModuleSettingsFilterGuid
        {
            get
            {
                return CRMImageGuidId;
            }
        }

		/// <summary>
		/// Attempt to cache the layout module name
		/// </summary>
		private string _layoutModule	=	string.Empty;
		string layoutModule
		{
			get
			{
				if (string.IsNullOrEmpty(_layoutModule))
				{
					_layoutModule = Config.ModulesPath + "/CRMImage/Layout/" + Settings[ImStr.ThumbnailLayout].Value;
					if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle layoutModule GET cached: {0}", _layoutModule),CrmImageTrace.Sw.Info);
				}
				return _layoutModule;
			}
		}

		private string _AlbumPath	=	string.Empty;
		public string AlbumPath
		{
			get
			{
				if (string.IsNullOrEmpty(_AlbumPath))
				{
                    if ( Settings[ImStr.CustomAlbumPath].ToBool() )
					    _AlbumPath = Settings[ImStr.AlbumPath].FullPath;
                    else _AlbumPath = portalSettings.CustomSettings[ImStr.AlbumPath].FullPath;
					if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle AlbumPath GET cached: {0}", _AlbumPath),CrmImageTrace.Sw.Info);
				}
				return _AlbumPath;
			}
		}
        
        
        /// <summary>
        /// Add a ToolTip to the loaded image
        /// Add the confirm script
        /// </summary>
        void AddToolTipImage(CRMImageItem ImgItem)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle AddToolTipImage BEG ImgItem.ID: {0}, ClientID: {1}.",ImgItem.ID,ImgItem.ClientID),CrmImageTrace.Sw.Info);
            Image img           =   (Image)ImgItem.FindControl("CrmImg");
            if ( !Object.Equals(img, null) )
            {
                string val      =   ImgItem.imageModifiedSrc;
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle AddToolTipImage img.ClientID: {0}, url: {1}.",img.ClientID,val),CrmImageTrace.Sw.Info);
                RadToolTipManager1.TargetControls.Add(img.ClientID, val, true);
            }
            // Add confirm delete
            ImageButton BtnDelImage =   (ImageButton)ImgItem.FindControl("BtnDelImage");
            if (!Object.Equals(BtnDelImage, null)  )
            {
                string msg                  =   LocalizeHelper.Localize("CONFIRM_DELETE", "Confirm Delete");
                string title                =   LocalizeHelper.Localize("DELETE", "Delete");
                ADNPage.setClientConfirmAttributes(BtnDelImage,msg,title);
            }
        }

        /// <summary>
		/// The Page_Load event on this page calls the BindData() method
		/// </summary>
		private void Page_Load(object sender, System.EventArgs e)
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle Page_Load IsPostBack: {0}, IsInAsyncPostBack: {1}.",IsPostBack,IsInAsyncPostBack),CrmImageTrace.Sw.Info);

            if (!UseSettingsFromAnotherModule)
            {
		        if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle Page_Load module not installes with its settings ModuleID: {0}, Title: {1}.",ModuleID,TitleText),CrmImageTrace.Sw.Info);
                Label notInstalled      =   new Label();
                notInstalled.CssClass   =   "Error";
                notInstalled.Text       =   "Installation for this module is not finalized, attach it to a CRMImage module before use";
                int idx                 =   Controls.IndexOf(dlPictures);
                Controls.AddAt(idx,notInstalled);
                return;
            }
            if (!IsPostBack)
            {
                // If delete ModuleButton is not display we must ensure that script is here
                dlPictures.RepeatDirection  =   RepeatDirection.Vertical;
                dlPictures.RepeatColumns    =   1;
                dlPictures.DataKeyField     =   ImStr.DBImageId;
            }
            // Only Bind when under CRM
            if ( IsUnderCRM )
                BindData();
	    }
	
        void dlPictures_ItemCreated(object sender, DataListItemEventArgs e)
        {
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle dlPictures_ItemCreated BEG IsUnderCRM: {0}, IsInAsyncPostBack: {1}, ItemIndex: {2}, Item.ItemType: {3}, Item.ID: {4}, Item.HasControls: {5}.", 
                    new object[]{IsUnderCRM,IsInAsyncPostBack,e.Item.ItemIndex,e.Item.ItemType,e.Item.ID,e.Item.HasControls()}),CrmImageTrace.Sw.Info);
            e.Item.ID   =   string.Format("Itm_{0}",e.Item.ItemIndex);
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle dlPictures_ItemCreated END Item.ID: {0}.", e.Item.ID),CrmImageTrace.Sw.Info);
        }
        /// <summary>
        /// This method fills a datalistItem with one record from db concerning one image
        /// To format values, it loads a template (an ascx control which inherits from CrmImageItem object)
        /// It fills the metadata propert of CrmImageItem from metadat readen from DB, then it adds usefull data concerning actual image display 
        /// allowing to display image, format edit and view urls, etc.
        /// Checks the metadata format version to allow evolutions
        /// </summary>
		private void CRMImageSingle_ItemDataBound(object sender, DataListItemEventArgs e)
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle CRMImageSingle_ItemDataBound BEG IsUnderCRM: {0}, IsInAsyncPostBack: {1}, ItemIndex: {2}, Item.ItemType: {3}, Item.ID: {4}, Item.HasControls: {5}.", 
                    new object[]{IsUnderCRM,IsInAsyncPostBack,e.Item.ItemIndex,e.Item.ItemType,e.Item.ID,e.Item.HasControls()}),CrmImageTrace.Sw.Info);
			try
			{
				if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle CRMImageSingle_ItemDataBound LoadControl: {0}.", layoutModule),CrmImageTrace.Sw.Info);
				CRMImageItem CRMImgItem				=   (CRMImageItem)Page.LoadControl(layoutModule);
				DbDataRecord di	=   (DbDataRecord)e.Item.DataItem;

				CRMImgItem.BindFromDB(di,AlbumPath,
                    0,
                    IsEditable,
                    IsDeletable,
                    RequestEntityTypename,
                    EntityName,
                    ModuleID,
                    e.Item.ItemIndex,
                    0,
                    -1,
                    "ASC");
                e.Item.Controls.Add(CRMImgItem);
                CRMImgItem.DataBind(); 
                AddToolTipImage(CRMImgItem);
		         if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle CRMImageSingle_ItemDataBound CRMImgItem added to Item.ID: {0}.",e.Item.ID),CrmImageTrace.Sw.Info);
			}
			catch (Exception ex)
			{
				if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageSingle CRMImageSingle_ItemDataBound ex : {0}.", ex),CrmImageTrace.Sw.Info);
                throw;
			}
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageSingle CRMImageSingle_ItemDataBound END.",CrmImageTrace.Sw.Info);
		}

		/// <summary>
        /// 
		/// The Binddata method on this User Control is used to
		/// obtain a DataReader of CRMImage information from the CRMImage
		/// table, and then databind the results to a templated DataList
		/// server control. It uses the AddonNice.CRMImageDB()
		/// data component to encapsulate all data functionality.
        /// If we are under CRM, we limit our action to display the EntityID asked by CRM or a default entityID for creation mode
        /// if not under CRM we display with paging all the existing images
		/// </summary>
		private void BindData()
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle BindData BEG IsInAsyncPostBack: {0}, IsUnderCRM: {1}.", 
                    IsInAsyncPostBack,IsUnderCRM),CrmImageTrace.Sw.Info);

            SqlDataReader dsCRMImage	=   null;
            try
            {
                CRMImageDB ImageDB      =   new CRMImageDB();
                dsCRMImage			    =   ImageDB.GetCRMImageByEntityId(EntityID); // we get the entityId from parameters
                if (dsCRMImage != null)
                {
                    // Under CRM, if we already have a row, we can't add more for CRMImage
                    // Outside CRM we can add more CRMImage, corresponding entities will be automatically added
                    if (dsCRMImage.HasRows)
                    {
                        if ( AddButton != null )
                            AddButton.Visible   = false;
                    }
                    dlPictures.DataSource       =   dsCRMImage;
                    dlPictures.DataBind();
                }
            }
            catch (Exception ex)
            {
                if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageSingle BindData ex: {0}", ex),CrmImageTrace.Sw.Info);
                throw;
            }
            finally
            {
                if (dsCRMImage != null)
                    dsCRMImage.Close();
            }
    		if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageSingle BindData END.",CrmImageTrace.Sw.Info);
		}

        /// <summary>
		/// Delete a CRMImage.  It  uses the AddonNice.CRMImageDB()
		/// data component to encapsulate all data functionality.
		/// </summary>
        void DeleteImage(string arg)
		{
            // Only attempt to delete the item if it is an existing item
			// (new items will have ImStr.ItemCrmID of Guid.Empty)
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle DeleteImage BEG args :{0}", arg),CrmImageTrace.Sw.Info);
            CRMImageDB ImageDB          =   new CRMImageDB();
            int ImageDBID               =   int.Parse(arg);
			
            string PathToDelete			=   Server.MapPath(AlbumPath) + "\\";

			SqlDataReader dr			=   null;
			string filename				=   string.Empty;
			string thumbnailFilename	=   string.Empty;
            Guid CrmImageId             =   Guid.Empty;
			try
			{
                dr						=   ImageDB.GetCRMImage(ImageDBID);
				// Read first row from database
				if (dr.Read())
				{
				    CrmImageId  	    =   (Guid)dr[ImStr.DBCrmImageId];
				    XmlDocument metadata	= new XmlDocument();
					metadata.LoadXml((string)dr[ImStr.DBMetadataXml]);
					filename			=   GetMetadata(metadata,ImStr.ModifiedFilename);
					thumbnailFilename	=   GetMetadata(metadata,ImStr.ThumbnailFilename);
				}
			}
			catch(Exception ex)
			{
				if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageSingle DeleteImage ex :{0}",ex),CrmImageTrace.Sw.Info);
                throw;
			}
			finally
			{
				if  ( dr != null )
					dr.Close();
			}


            //Delete the record from database.
            try
            {
                ImageDB.DeleteCRMImage(ImageDBID);
            }
            catch (Exception ex)
            {
                if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageSingle DeleteImage ex :{0}", ex),CrmImageTrace.Sw.Info);
                throw;
            }

			//Delete the files
			try
			{
				File.Delete(PathToDelete + filename);
				File.Delete(PathToDelete + thumbnailFilename);
			}
			catch(Exception ex1)
			{
				// We don't really have much to do at this point
                if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageSingle DeleteImage Error deleting physical files ex :{0}", ex1),CrmImageTrace.Sw.Info);
			}
            // We must rebind 
            BindData();
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CRMImageSingle DeleteImage END",CrmImageTrace.Sw.Info);
		}


        void dlPictures_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle dlPictures_ItemCommand BEG CommandName: {0}, CommandArgument: {1}",e.CommandName,e.CommandArgument),CrmImageTrace.Sw.Info);
            if (e.CommandName == "DeleteImage")
            {
                DeleteImage(e.CommandArgument.ToString());
            }
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageSingle dlPictures_ItemCommand END CommandName: {0}, CommandArgument: {1}",e.CommandName,e.CommandArgument),CrmImageTrace.Sw.Info);
        }


        /// <summary>
		/// Default constructor
		/// This module has no special module options, it is dedicated to share its options with an occurence of a CRMImage Module
        /// The install proc take care to setup this link
		/// </summary>
		public CRMImageSingle()
		{
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageSingle Ctor Called.",CrmImageTrace.Sw.Info);
		}

        #region Std overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageSingle Page_PreInit BEG.",CrmImageTrace.Sw.Info);
            AddText     =   "ADD"; //"Add New CRMImage"
            AddUrl      =   Config.ModulesPath + "/CRMImage/CRMImageEdit.aspx";
			base.Page_PreInit(sender, e);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageSingle Page_PreInit END.",CrmImageTrace.Sw.Info);
        }

        override protected void OnInit(EventArgs e)
		{
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageSingle OnInit BEG.",CrmImageTrace.Sw.Info);
			InitializeComponent();
			base.OnInit(e);
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CRMImageSingle OnInit END.",CrmImageTrace.Sw.Info);
		}

		private void InitializeComponent()
		{
            dlPictures.ItemCreated      +=  new DataListItemEventHandler(dlPictures_ItemCreated);
            dlPictures.ItemDataBound    +=  new DataListItemEventHandler(CRMImageSingle_ItemDataBound);
            dlPictures.ItemCommand      +=  new DataListCommandEventHandler(dlPictures_ItemCommand);
            Load                        +=  new EventHandler(Page_Load);
		}

		#endregion

	}
}
